/**
 * 表单验证
 */
import { checkUserDuplicate } from "../api/api";

export default function validator(target, validator, errorMsg, callback) {
  return new Proxy(target, {
      _validator: validator,
      set(target, key, value, proxy) {
          let _value = '';
          if(!!value){
            _value = value.trim();
          }
          let errMsg = errorMsg
          if (_value == '') {
            callback({
              state: false,
              key: errMsg[key].errKey,
              msg: `${errMsg[key].name}不能为空！`
            })
            return true
          }
          let va = this._validator[key]
          if(!va(_value)){
            callback({
              state: false,
              key: errMsg[key].errKey,
              msg: `${errMsg[key].errmsg}`
            })
            return true
          }
          target[key] = _value
          callback({
            state: true,
            key: errMsg[key].errKey
          })
          if(key === 'username'){
            checkUserDuplicate({ 
              username: _value,
              UUID: sessionStorage.getItem('UUID')
            }).then(res => {
              if (res.duplicate == true) {
                callback({
                  state: false,
                  key: errMsg[key].errKey,
                  msg: `${errMsg[key].name}重复`
                })
              } 
            });
          } 
          return true
      }
  })
}